"""
Простая защита ядра от изменеий кода.

Author: Milinuri Nirvalen
Ver: 1.1.2 (5)
"""

from chiori import Colors
from chiori import Config
from chiori import Plugin

import hashlib
import os


p = Plugin(name='защита ядра', desc='защита ядра от изменений')

# func
# ====

def get_file_hash(path):
	with open(path, 'rb') as f:
		data = f.read()
		h = hashlib.md5(data)
		return h.hexdigest()


def dict_table(data={}, name='─', size=None, color='\033[0m', model=['h', 'f']):
	c = Colors()
	if not size:
		size = max(map(lambda x: max([len(x[0]), len(x[1])]), data.items()))
		if size > 30:
			size = 32

	lines = []
	for k, v in data.items():
		i = 0
		length = max(map(lambda x: len(c.rc(x)), [k, v]))

		while True:
			offset = size*i
			if length > size:
				lines.append((k[offset:offset+size], v[offset:offset+size]))
				i += 1
				length -= size
			else:
				lines.append((k[offset:], v[offset:]))
				if i:
					lines.append(("─"*size, "─"*size))
				break

	if 'h' in model:
		print(f'{color}┌─\033[0m {name} {color}{"─"*(size-1-len(c.rc(name)))}┬{"─"*(size+2)}┐\033[0m')
	for k, v in lines:
		print(f'{color}│ \033[0m{k}{" "*(size-len(c.rc(k)))} {color}│ \033[0m{" "*(size-len(c.rc(v)))}{v} {color}│\033[0m')
	if 'f' in model:
		print(f'{color}└{"─"*(size+2)}┴{"─"*(size+2)}┘\033[0m')


def update_hashes():
	c = Config('core-protect')
	c.group_data['hashes'] = {}

	for x in os.listdir('chiori'):
		path = os.path.join('chiori', x)

		if os.path.isfile(path):
			h = get_file_hash(path)
			c.group_data['hashes'][x] = h

	dict_table(c.group_data["hashes"], 'new hashes')
	c.save()


@p.eventHandler('init')
async def _(app):
	c = Config('core-protect', {"shutdown":True, 'hashes':{}})
	if not c.group_data['hashes']:
		update_hashes()

	files = os.listdir('chiori')
	p.log('check chiori files')
	res = {}
	warns = 0
	for k, v in c.group_data["hashes"].items():
		if k not in files:
			res[f"{p.l.cyan}{k}".strip('.py')] = f"{p.l.lred}not found"
			warns += 1
			continue

		h = get_file_hash(os.path.join('chiori', k))
		if h != v:
			res[f"{p.l.cyan}{k}".strip('.py')] = f'{p.l.lyellow}MODIFIED'
			warns += 1
		else:
			res[f"{p.l.cyan}{k}".strip('.py')] = f"{p.l.lgreen}ok"
	dict_table(res, f'{p.l.lblue}hashes', 15, p.l.gray)

	if warns:
		dict_table({f"{p.l.lyellow}warns":str(warns)}, size=15, color=p.l.gray, model=['f'])
		if c.group_data["shutdown"]:
			await app.stopEvent()

@p.command('<u(pdate) hash>', uhash='обновить хеш-суммы файлов')
async def upddateFileHashes(event, ctx):
	update_hashes()
